﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WorkBasket.Data.Entities;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using WorkBasket.Models;

namespace WorkBasket.Controllers.Api
{
    public class DomainUnitController : ApiController
    {
        private SOC soc = new SOC(new MyContext());

        [HttpPost]
        [Route("api/DomainUnit/ValidateDomain")]
        public IHttpActionResult ValidateDomain(Domain domain)
        {

     
            //change this to return the object id so you can populate the json and attach to the unit properly.  This will 
            //allow it to upload post to the database right

            if (AuthFunctions.ValidateEnterpriseConnection(domain.DomainName))
            {
                Domain dom = soc.Domains.Where(c => c.DomainName.ToLower() == domain.DomainName.ToLower() && c.DomainKey == domain.DomainKey).FirstOrDefault();

                if (dom != null)
                {
                    return Json(dom);
                }
                else
                {
                    return Ok();
                }

            }
            else
            {
                return Ok();
            }
        }
        [Route("api/DomainUnit/save")]
        public IHttpActionResult Post([FromBody]  DomainUnit value)
        {
            try
            {
                if (value.DomainUnitID == 0 )
                {
                    soc.DomainUnits.Add(value);
                }
                else
                {
                    soc.DomainUnits.Update(value);

                }
                soc.CommitChanges();
                 return Json(new DataReturn(string.Empty, value));
            }
                catch (Exception e)
            {
                return new System.Web.Http.Results.ExceptionResult(e, this);
            }
        }

        [Route("api/DomainUnit/GetByUnitID/{UnitID}")]
        public IHttpActionResult GetByUnitID(int UnitID)
        {


           return Json( soc.Execute<Domain>("GetDomainsByUnitID @UnitID", new System.Data.SqlClient.SqlParameter("UnitID", UnitID)));



        }
    }
}
